using Microsoft.Web.WebView2.Core;
using Microsoft.Web.WebView2.Wpf;
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;

namespace WebBrowser
{
    public class BrowserTab
    {
        public TabItem TabItem { get; private set; }
        public WebView2 WebView { get; private set; }
        public TextBlock HeaderText { get; private set; }
        
        public event EventHandler<CoreWebView2NewWindowRequestedEventArgs>? NewWindowRequested;
        public event EventHandler<string>? FaviconChanged;
        public event EventHandler<(string title, string url, string faviconUrl)>? NavigationCompleted;
        
        public BrowserTab(string url = "about:blank")
        {
            // Create the WebView2 control
            WebView = new WebView2
            {
                HorizontalAlignment = HorizontalAlignment.Stretch,
                VerticalAlignment = VerticalAlignment.Stretch
            };
            
            // Create the tab item
            TabItem = new TabItem();
            
            // Create the header with text and close button
            var headerPanel = new DockPanel();
            HeaderText = new TextBlock
            {
                Text = "New Tab",
                Width = 120,
                TextTrimming = TextTrimming.CharacterEllipsis,
                VerticalAlignment = VerticalAlignment.Center,
                FontSize = 12
            };
            
            var closeButton = new Button
            {
                Content = "×",
                Background = System.Windows.Media.Brushes.Transparent,
                BorderThickness = new Thickness(0),
                Padding = new Thickness(0),
                Margin = new Thickness(5, 0, 0, 0),
                VerticalContentAlignment = VerticalAlignment.Center,
                HorizontalContentAlignment = HorizontalAlignment.Center,
                Width = 20,
                Height = 20,
                FontSize = 14,
                FontWeight = FontWeights.Bold,
                Cursor = Cursors.Hand
            };
            
            // We'll handle the close button click in MainWindow.xaml.cs
            
            headerPanel.Children.Add(HeaderText);
            headerPanel.Children.Add(closeButton);
            DockPanel.SetDock(closeButton, Dock.Right);
            
            TabItem.Header = headerPanel;
            
            // Initialize the WebView2 control
            InitializeWebViewAsync(url);
        }
        
        private async void InitializeWebViewAsync(string url)
        {
            try
            {
                // Initialize the WebView2 control
                await WebView.EnsureCoreWebView2Async(null);
                
                // Handle navigation completed event
                WebView.NavigationCompleted += (s, e) => 
                {
                    // Update the URL in the address bar if this tab is selected
                    if (TabItem.IsSelected && TabItem.Parent is TabControl tabControl)
                    {
                        // Update URL in the main window if this tab is selected
                        if (WebView.Source != null)
                        {
                            var urlText = WebView.Source.ToString();
                            Application.Current.Dispatcher.Invoke(() => {
                                if (Application.Current.MainWindow is MainWindow mainWindow)
                                {
                                    mainWindow.UpdateUrlTextBox(urlText);
                                }
                            });
                        }
                    }
                    
                    // Record navigation in history
                    if (e.IsSuccess && WebView.Source != null)
                    {
                        var title = WebView.CoreWebView2?.DocumentTitle ?? "New Tab";
                        var url = WebView.Source.ToString();
                        var faviconUrl = WebView.CoreWebView2?.FaviconUri ?? "";
                        NavigationCompleted?.Invoke(this, (title, url, faviconUrl));
                    }
                };
                
                // Handle document title changed event
                WebView.CoreWebView2.DocumentTitleChanged += (s, e) => 
                {
                    var title = WebView.CoreWebView2.DocumentTitle;
                    HeaderText.Text = string.IsNullOrEmpty(title) ? "New Tab" : title;
                };
                
                // Handle favicon changed event
                WebView.CoreWebView2.FaviconChanged += (s, e) => 
                {
                    if (WebView.CoreWebView2.FaviconUri != null)
                    {
                        FaviconChanged?.Invoke(this, WebView.CoreWebView2.FaviconUri);
                    }
                };
                
                // Handle new window requests - open all links in the same tab
                WebView.CoreWebView2.NewWindowRequested += (s, e) => 
                {
                    // Cancel the new window creation
                    e.Handled = true;
                    
                    // Navigate to the requested URI in the current tab
                    if (!string.IsNullOrEmpty(e.Uri))
                    {
                        WebView.CoreWebView2.Navigate(e.Uri);
                    }
                };
                
                // Navigate to the URL
                if (!string.IsNullOrEmpty(url))
                {
                    if (!url.StartsWith("http://") && !url.StartsWith("https://") && !url.StartsWith("about:"))
                    {
                        url = "https://" + url;
                    }
                    
                    WebView.CoreWebView2.Navigate(url);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"WebView2 initialization failed: {ex.Message}", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
        
        public void Navigate(string url)
        {
            if (WebView.CoreWebView2 != null)
            {
                if (!string.IsNullOrEmpty(url))
                {
                    if (!url.StartsWith("http://") && !url.StartsWith("https://") && !url.StartsWith("about:"))
                    {
                        url = "https://" + url;
                    }
                    
                    try
                    {
                        WebView.CoreWebView2.Navigate(url);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show($"Navigation failed: {ex.Message}", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                    }
                }
            }
        }
        
        public void GoBack()
        {
            if (WebView.CoreWebView2 != null && WebView.CoreWebView2.CanGoBack)
            {
                WebView.CoreWebView2.GoBack();
            }
        }
        
        public void GoForward()
        {
            if (WebView.CoreWebView2 != null && WebView.CoreWebView2.CanGoForward)
            {
                WebView.CoreWebView2.GoForward();
            }
        }
        
        public void Refresh()
        {
            if (WebView.CoreWebView2 != null)
            {
                WebView.CoreWebView2.Reload();
            }
        }
        
        public bool CanGoBack => WebView.CoreWebView2 != null && WebView.CoreWebView2.CanGoBack;
        public bool CanGoForward => WebView.CoreWebView2 != null && WebView.CoreWebView2.CanGoForward;
    }
}